var Q = require('q'),
    mongoose = require('mongoose'),
    SocketIo = require('../../../Base/server/controllers/Socket'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');

//根据根据工单ID查找全部看板需求
exports.findOneByMoId = function(MoId, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.findOne({ MO: MoId }, null, function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板需求错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

//根据条件获取看板信息
exports.findRecordsByCondition = function(condition, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find(condition, null, [{
        path: "MO",
        select: "Code LotNumber ItemMaster",
        populate: [{
            path: "ItemMaster",
            select: "Code Name",
            model: 'ItemMaster'
        }]
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

//通过要货部门查找看板信息
exports.queryDemandByDepartment = function(demandDepartment, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find({ DemandDepartment: demandDepartment }, null, [{
        path: "ItemMaster",
        select: "Code Name",
        model: 'ItemMaster'
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};


//根据（物料+尺寸+外观）和仓库ID和需求部门查找  要货看板信息
exports.findOneKanbanDemand = function(item, wareHouseId, departmentId, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.findOne({
        ItemMaster: item.ItemMaster,
        DescSeg1: item.DescSeg1,
        DescSeg2: item.DescSeg2,
        WareHouse: wareHouseId,
        DemandDepartment: departmentId
    }, [{
        path: "ItemMaster",
        select: "Code Name"
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
//根据（物料+尺寸+外观）和仓库ID查找  备货看板信息
exports.findOneGiveKanbanDemand = function(item, wareHouseId, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find({
        ItemMaster: item.ItemMaster,
        DescSeg1: item.DescSeg1,
        DescSeg2: item.DescSeg2,
        WareHouse: wareHouseId
    }, null, [{
        path: "ItemMaster",
        select: "Code Name"
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

//根据仓库ID和需求部门 查找要货看板信息
exports.findAllKanbanDemand = function(wareHouseId, departmentId, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find({
        WareHouse: wareHouseId,
        DemandDepartment: departmentId
    }, null, [{
        path: "ItemMaster",
        select: "Code Name"
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

//根据根据工单ID和待转区ID查找看板需求
exports.findOne = function(moId, wareHouseId) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("KanbanDemand");
    entity.findOne({ MO: moId, WareHouse: wareHouseId }, null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板需求错误，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(record);
    });

    return deferred.promise;
};

//创建看板需求
exports.insert = function(demandData) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("KanbanDemand");
    entity.insert(demandData, function(err, newDemand) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '新增错误';
            newErr.message = '新增看板需求错误，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(newDemand);
    });

    return deferred.promise;
};
//更新看板表的数据
exports.updateByValue = function(_id, value, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.updateByValue({ _id: _id }, value, function(err, result) {
        completeFun(err, result);
    });
};

/**
 *
 * @param condition
 * @param num
 * @param completeFun
 */
exports.updateByCondition = function(flg, condition, num, completeFun) {
    var kanbanDemandModel = mongoose.model('KanbanDemand');
    if (flg === 'pick') {
        kanbanDemandModel.update(condition, { $inc: { TotalStockQty: num } }, function(err, result) {
            if (err) {
                completeFun(err);
            } else {
                SocketIo.emit(condition.WareHouse.toString(), num);
                completeFun(null, result);
            }
        });
    } else {
        kanbanDemandModel.update(condition, { $inc: { TotalReceiveQty: num } }, function(err, result) {
            if (err) {
                completeFun(err);
            } else {
                SocketIo.emit(condition.WareHouse.toString(), num);
                completeFun(null, result);
            }
        });
    }

};


//通过仓库查找部门
exports.queryDemandByWareHouse = function(condition, completeFun) {
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find(condition, null, [{
        path: "DemandDepartment",
        select: "Code Name",
        model: 'Department'
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询部门错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
